<template>
  <div>
    <el-select
      v-model="selectedValue"
      filterable
      remote
      :remote-method="handleSearch"
      :loading="loading"
      style="width: 100%"
      placeholder="请选择"
    >
      <el-option
        v-for="item in options"
        :key="item[valueKey]"
        :label="item[labelKey]"
        :value="item[valueKey]"
      ></el-option>
      <el-option
        v-if="options.length === 0 && !loading"
        value=""
        disabled
      >
        无数据
      </el-option>
    </el-select>
    <el-pagination
      v-if="total > pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  name: 'SelectWithPage',
  props: {
    valueKey: {
      type: String,
      default: 'id'
    },
    labelKey: {
      type: String,
      default: 'name'
    },
    searchKey: {
      type: String,
      default: 'search'
    },
    otherParams: {
      type: Object,
      default: () => ({})
    },
    requestUrl: {
      type: Function,
      required: true
    },
    pageSize: {
      type: Number,
      default: 10
    },
    value: {
      default: null
    }
  },
  data() {
    return {
      selectedValue: this.value,
      options: [],
      loading: false,
      total: 0,
      currentPage: 1
    };
  },
  watch: {
    value(newVal) {
      this.selectedValue = newVal;
    },
    currentPage(newVal) {
      this.fetchData();
    },
    pageSize(newVal) {
      this.currentPage = 1; // Reset page when page size changes
      this.fetchData();
    }
  },
  methods: {
    handleSearch(queryString) {
      this.otherParams[this.searchKey] = queryString;
      this.currentPage = 1; // Reset page when searching
      this.fetchData();
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    fetchData() {
      this.loading = true;
      this.requestUrl({
        ...this.otherParams,
        page: this.currentPage,
        limit: this.pageSize
      }).then(res => {
        this.options = res.list;
        this.total = res.total;
        this.loading = false;
      }).catch(error => {
        console.error('Failed to fetch data:', error);
        this.loading = false;
      });
    },
    // 同步父组件的selectedValue
    syncSelectedValue(newValue) {
      this.$emit('update:select-value', newValue);
    }
  },
  mounted() {
    this.fetchData(); // 初始化时加载数据
  },
  computed: {
    // 计算属性，用于同步父组件的value
    syncValue: {
      get() {
        return this.selectedValue;
      },
      set(value) {
        this.selectedValue = value;
        this.syncSelectedValue(value);
      }
    }
  }
};
</script>
